package com.humngyang.com.hmy.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.humngyang.com.hmy.entity.Authority;
import com.humngyang.com.hmy.entity.Role;
import com.humngyang.com.hmy.entity.RoleAuthority;
import com.humngyang.com.hmy.mapper.RoleAuthorityMapper;
import com.humngyang.com.hmy.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class RoleAuthorityService {


    @Autowired
    private RoleAuthorityMapper roleAuthorityMapper;

    @Autowired
    RoleService roleService;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    AuthorityService authorityService;

    /**
     * Author : hmy
     *
     * @date 2020/2/26 14:45
     * describution : 查询所有的角色权限表
     **/

    public List<RoleAuthority> getAllAuthority() {
        List<RoleAuthority> roleAuthorities = roleAuthorityMapper.selectList(null);
        if (!CollectionUtils.isEmpty(roleAuthorities)) {
            return roleAuthorities;
        } else {
            return Collections.EMPTY_LIST;
        }
    }


    /**
     * Author : hmy
     *
     * @date 2020/2/28 5:36
     * describution : 查询树状结构的角色权限数据
     **/
    public List<Map<String, Object>> getAllAuthorityMap(String roleName) {
        List<Map<String, Object>> maps = roleAuthorityMapper.selectMaps(new QueryWrapper<RoleAuthority>().eq("rolename", roleName));
        if (!CollectionUtils.isEmpty(maps)) {
            return maps;
        } else {
            return Collections.EMPTY_LIST;
        }
    }

    //    根据角色获取对应角色的权限数据
    public List<Map<String, Object>> getTreeAuthorityByRole() {
        List<Map<String, Object>> allRole = roleService.getAllRoleMap();
        for (Map<String, Object> role : allRole) {
            String rolename = (String) role.get("rolename");
            List<Map<String, Object>> allAuthorityMap = getAllAuthorityMap(rolename);
            List<Map<String, Object>> maps = parseTree(allAuthorityMap);
            role.put("authirity", maps);
        }
        return allRole;
    }


    public List<Map<String, Object>> parseTree(List<Map<String, Object>> list) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Map<String, Object> tmpMap = new HashMap<String, Object>();
        for (int i = 0, l = list.size(); i < l; i++) {
            tmpMap.put(String.valueOf(list.get(i).get("authroid")), list.get(i));
        }
        for (int i = 0, l = list.size(); i < l; i++) {
            Map<String, Object> map = list.get(i);
            //tmpMap存储的均为id为key的键值对，如果以pid为key可以取出对象，则表明该元素是父级元素
            if (tmpMap.get(map.get("pid")) != null && (map.get("authroid") != map.get("pid"))) {
                //给当前这个父级map对象中添加key为children的ArrayList
                if ((tmpMap.get(map.get("pid")) != null) && ((Map<String, Object>) tmpMap.get(map.get("pid"))).get("children") == null) {
                    ((Map<String, Object>) tmpMap.get(map.get("pid"))).put("children", new ArrayList<Map<String, Object>>());
                }
                Map<String, Object> tmap = (Map<String, Object>) tmpMap.get(map.get("pid"));
                ArrayList<Map<String, Object>> tArrayList = (ArrayList<Map<String, Object>>) tmap.get("children");
                tArrayList.add(list.get(i));            //没有父节点
            } else {
                resultList.add(list.get(i));
            }
        }
        return resultList;
    }


    /**
     * Author : hmy
     *
     * @date 2020/2/28 16:34
     * describution : 根据角色权限表主键id删除权限
     **/

    public Integer deleteById(RoleAuthority roleAuthority) {
        int i = roleAuthorityMapper.delete(new QueryWrapper<RoleAuthority>()
                .eq("roleid", roleAuthority.getRoleid()).eq("authroid", roleAuthority.getAuthroid()));
        return i;
    }

    /**
     * Author : hmy
     *
     * @date 2020/3/1 9:23
     * describution : 删除二级权限， 包括二级权限下的三级权限
     **/

    public Integer secondDeleteById(RoleAuthority roleAuthority) {
        int delete = roleAuthorityMapper.delete(new QueryWrapper<RoleAuthority>()
                .eq("roleid", roleAuthority.getRoleid())
                .and(i -> i
                        .eq("authroid", roleAuthority.getAuthroid())
                        .or()
                        .eq("pid", roleAuthority.getAuthroid()))
        );
        return delete;
    }


    /**
     * Author : hmy
     *
     * @date 2020/3/1 10:32
     * describution :根据角色查找所有的权限
     **/

    public List<Map<String, Object>> getRoleList(Role role) {
        List<Map<String, Object>> list = roleAuthorityMapper.selectMaps(new QueryWrapper<RoleAuthority>()
                .eq("roleid", role.getRoleid()));
        if (CollectionUtils.isEmpty(list)) {
            return Collections.EMPTY_LIST;
        }
        List<Map<String, Object>> roleid = parseTree(list);
        return roleid;
    }

    /**
     * Author : hmy
     *
     * @date 2020/3/1 11:15
     * describution :根据角色权限的id集合删除对应的数据
     **/

    public Integer deleteByIds(List<String> list) {
        int i = roleAuthorityMapper.deleteBatchIds(list);
        if (i > 0) {
            return i;
        }
        return 0;
    }

    /**
     * Author : hmy
     * @date 2020/3/2 17:53
     * describution : 添加权限设置
     **/
    @Transactional
    public void addRoleAuth(Map<String, Object> map) {
        List<String> list = (List<String>) map.get("id");
        Map<String,Object> role = (Map<String, Object>) map.get("role");
        Map<String, Object> authMap = new HashMap<>();
        List<Authority> allAuthrority = authorityService.getAllAuthrority();
        for (Authority authority : allAuthrority) {
            authMap.put(authority.getId(), authority);
        }

        List<RoleAuthority> insertList = new ArrayList<>();
        roleAuthorityMapper.delete(new QueryWrapper<RoleAuthority>().eq("roleid", (String) role.get("roleid")));
        for (String authid : list) {
            RoleAuthority ra = new RoleAuthority();
            ra.setId(UUID.randomUUID().toString().replace("-", ""));
            ra.setRoleid((String) role.get("roleid"));
            ra.setRolename((String) role.get("rolename"));
            ra.setAuthroid(authid);
            Authority authority = (Authority) authMap.get(authid);
            ra.setAuthorityname(authority.getAuthorityname());
            ra.setPid(authority.getPid());
            insertList.add(ra);
            roleAuthorityMapper.insert(ra);
        }
    }



}
